iT邦幫忙

0

Day 11: 344. Reverse String

  • 分享至 

  • xImage
  •  

Write a function that reverses a string. The input string is given as an array of characters s.

You must do this by modifying the input array in-place with O(1) extra memory.

Example 1:
Input: s = ["h","e","l","l","o"]
Output: ["o","l","l","e","h"]
Example 2:
Input: s = ["H","a","n","n","a","h"]
Output: ["h","a","n","n","a","H"]
解題思路
1.將字元陣列s反轉(原地操作,不可使用額外陣列)。
2.解法概念:雙指標交換
一個指標從左邊開始 (left = 0)。
一個指標從右邊開始 (right = s.length - 1)。
3.每次交換兩個字元後,left++、right--。
停止條件:
當left >= right時,反轉完成。
https://ithelp.ithome.com.tw/upload/images/20251014/20179424OXWB0lI0rf.png


圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言